package com.soul.dubbo.api.mongo;

import com.soul.model.mongo.Friend;
import com.soul.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author mdoya
 * @version 1.0
 * @description:
 */
@Slf4j
@DubboService
public class ContactApiImpl implements ContactApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询好友列表分页
     *
     * @param page     每页
     * @param pagesize 每页条数
     * @param userId   当前用户id
     * @return PageResult
     */
    @Override
    public PageResult<Friend> findpageContacts(Long page, Long pagesize, Long userId) {
        // 1. 构建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        // 2. 查询总条数
        long count = mongoTemplate.count(query, Friend.class);
        long startIndex = (page - 1 ) * pagesize;
        List<Friend> friendList = null;
        if (count > startIndex){
            // 3. 分页
            query.skip((page - 1 ) * pagesize).limit(pagesize.intValue());
            query.with(Sort.by(Sort.Direction.DESC,"created"));
            // 4. 执行查询
            friendList = mongoTemplate.find(query, Friend.class);
            // 5. 封装数据
        }
        return new PageResult<Friend>(page,pagesize,count,friendList);
    }
}
